package com.qipay.sp.excutor.mdfu;

import com.alibaba.fastjson.JSONObject;
import com.qipay.baas.model.Order;
import com.qipay.order.config.OrderStateEnum;
import com.qipay.order.service.OrderService;
import com.qipay.scalar.type.ApiTypeEnum;
import com.qipay.sp.excutor.AbstractExcutor;
import com.qipay.utils.MD5Util;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Component
public class MdWxNativeExcutor extends AbstractExcutor {

    private final static String API_URL="api_url";
    @Autowired
    OrderService orderService;

    @Override
    protected ApiTypeEnum getApiTypeEnum() {
        return ApiTypeEnum.WX_NATIVE;
    }

    @Override
    protected Map<String, Object> getApiParams(Order order, Map<String, Object> spconfig, Map<String, Object> extendOrderParams) {
        Map<String, Object> apiParams = new HashMap<>();
        apiParams.put("version","1.0");
        apiParams.put("sdorderno", order.getTradeNo());
        apiParams.put("total_fee", new BigDecimal(order.getAmount()).divide(new BigDecimal("100"),2,BigDecimal.ROUND_DOWN));
        apiParams.put("paytype","cbkpay");//cbkalipay：支付宝；cbkpay：微信支付
//        apiParams.put("get_code","1");

        return apiParams;
    }

    @Override
    protected Map<String, Object> run(Map<String, Object> spconfig, Map<String, Object> params) throws Exception {
        Object apiUrl = getVal(spconfig, API_URL);
        Object customerid = getVal(spconfig, "merchant_no");//商户uid
        Object notifyUrl= getVal(spconfig, "notify_url");
        Object returnUrl= getVal(spconfig, "return_url");
        Object key= getVal(spconfig, "key");

        params.put("customerid",customerid);
        params.put("notifyurl",notifyUrl);
        params.put("returnurl",returnUrl);
        String keyStr =generateStr(params,key.toString());

        String sign = MD5Util.sign(keyStr,"utf-8").toLowerCase();
        params.put("sign",sign);

        String result = generateAutoSubmitHtml(params,apiUrl.toString());

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("result_code", "0");
        resultMap.put("pay_info", result);

        return resultMap;
    }

    private String generateStr(Map<String, Object>params ,String key){
        return "version="+params.get("version")+"&customerid="+params.get("customerid")+"&total_fee="+params.get("total_fee")+
                "&sdorderno="+params.get("sdorderno")+"&notifyurl="+params.get("notifyurl")+"&returnurl="+params.get("returnurl")
                +"&"+key;
    }
}
